<?php

namespace app\model;

use think\facade\Db;

class TaskModel {

	public static function modify_driver($param) {

		Db::startTrans();
		try {
			$data['is_receive'] = 1;
			if ($param['driver_id'] > 0 && $param['car_id'] == 0) {
				$taskInfo = Db::table('xl_normal_task')->where(['id' => $param['id']])->find();
				if ($taskInfo['car_id'] > 0) {
					$data['task_status'] = 2;
				}
				$data['driver_id'] = $param['driver_id'];
			}
			if ($param['car_id'] > 0 && $param['driver_id'] == 0) {
				$taskInfo = Db::table('xl_normal_task')->where(['id' => $param['id']])->find();
				if ($taskInfo['driver_id'] > 0) {
					$data['task_status'] = 2;
				}
				$data['car_id'] = $param['car_id'];
			}
			if ($param['driver_id'] > 0 && $param['car_id'] > 0) {
				$data['car_id'] = $param['car_id'];
				$data['driver_id'] = $param['driver_id'];
				$data['task_status'] = 2;
			}
			Db::table('xl_normal_task')->where(['id' => $param['id']])->update($data);
			// 提交事务
			Db::commit();
			return true;
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return false;
		}
	}

	public static function modifyRemarks($param) {

		Db::startTrans();
		try {
			Db::table('xl_normal_task')->where(['id' => $param['id']])->update(['task_remarks' => $param['task_remarks']]);
			// 提交事务
			Db::commit();
			return true;
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return false;
		}
	}

	public static function modifyTaskStatus($param) {

		Db::startTrans();
		try {

			$record = Db::table('xl_normal_task')->where(['id' => $param['id'], 'task_status' => 6])->find();
			if (empty($record)) {
				return false;
			}

			$task_status = $param['status'] == 0 ? 7 : 5;

			Db::table('xl_normal_task')->where(['id' => $param['id']])->update(['task_status' => $task_status]);
			// 提交事务
			Db::commit();
			return true;
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return false;
		}
	}

	public static function exportByMonth($param): array
	{

		if ($param['stime'] == "" || $param['etime'] == "") {
			returnFail(29101, '请求时间传入错误');
		}
		$sql = "SELECT normal_task.id,
	normal_task.DATE as date,
	normal_task.car_id,
	task_remarks,
	network_ids,
	normal_task.warehouse_ids,
	normal_task.requirement_time,
	normal_task.task_type,
	drivers.NAME AS driver_names,
	linedata.line_no AS line_nos,
	cars.car_plate_number AS car_name  FROM xl_normal_task  normal_task   left join xl_driver drivers on normal_task.driver_id=drivers.id left join xl_parnter_line linedata on linedata.id=  normal_task.line_id  left join xl_cars cars on  normal_task.car_id=cars.id WHERE normal_task.date  >= :date1   AND normal_task.date  <= :date2  and   task_status >=1";

		$list = Db::query($sql, ['date1' => $param['stime'], 'date2' => $param['etime']]);

		$networkData = Db::table('xl_networks')
			->field('id,name')
			->select()->toArray();

		$warehouseData = Db::table('xl_warehouse')
			->field('id,name')
			->select()->toArray();

		foreach ($list as $k => $v) {

			// $list[$k]['networks']="";
			// $list[$k]['warehouse']="";
			$list[$k]['network_count'] = count(explode(",", $v['network_ids']));
			$list[$k]['network_arrive_count'] = Db::table('xl_normal_task_arrive_detail')->where('net_id', 'in', $v['network_ids'])->where('type', 2)->where('task_id', $v['id'])->count();
			$listn = "";
			$network_ids = explode(",", $v['network_ids']);
			$sql = "select id,name from xl_networks where id in ( " . $v['network_ids'] . " ) order by field (id," . $v["network_ids"] . ")";
			$res = Db::query($sql);
			foreach ($res as $k1 => $v1) {
				if ($listn == "") {
					$listn .= $v1['name'];
				} else {
					$listn .= "," . $v1['name'];
				}

			}
			$list[$k]['listn'] = $listn;

			//  $net= Db::name('networks')->where('id','in',$network_ids)->fieldRaw('GROUP_CONCAT(name) as networks')
			//   ->fieldRaw('order by field (id,$v["network_id"])')->find();
			$normalTask[$k]['networks_list'] = $list;
		}

		return $list;
	}

	public static function lists($param)
    {
        try {
            $source = PartnerUser::where('id',request()->param('uid'))->value('source');
            $where[] = [
                    'task.uid', 'like',$source."%" ,
            ];
            $where[] = [
                    'task.partner_id', '=', $param['partner_id'],
            ];
            if (isset($param['task_status']) && $param['task_status'] > 0 && $param['task_status'] != 2) {
                if ($param['task_status'] == 3) {
                    $param['task_status'] = 4;
                } else if ($param['task_status'] == 4) {
                    $param['task_status'] = 5;
                }
                $where[] = ['task.task_status', '=', $param['task_status']];
            }
            if (isset($param['task_status']) && $param['task_status'] > 0 && $param['task_status'] == 2) {
                $where[] = ['task.task_status', 'in', [2, 3]];
            }
            if (isset($param['no']) && !empty($param['no'])) {
                $where[] = ['task.no', '=', $param['no']];
            }

            if (isset($param['line_id']) && !empty($param['line_id'])) {
                $where[] = ['task.line_id', '=', $param['line_id']];
            }

            if (isset($param['car_id']) && !empty($param['car_id'])) {
                $where[] = ['task.car_id', '=', $param['car_id']];
            }

            if (isset($param['driver_id']) && !empty($param['driver_id'])) {
                $where[] = ['task.driver_id', '=', $param['driver_id']];
            }

            if (isset($param['task_date']) && ($param['task_date'] == 1)) {
                $where[] = ['task.date', '=', getTodayDate()];
            } else {
                $where[] = ['task.date', '<', getTodayDate()];
            }

            if (isset($param['line_no']) && !empty($param['line_no'])){
                $where[]=['line.line_no','=',$param['line_no']];
            }
            if (isset($param['company_name']) && !empty($param['company_name'])){
                $where[]=['company.name','like', '%' . $param['company_name'] . '%'];
            }
            if (isset($param['driver_name']) && !empty($param['driver_name'])){
                $where[]=['driver.name','like', '%' .$param['driver_name'] . '%'];
            }
            if (isset($param['car_no']) && !empty($param['car_no'])){
                $where[]=['car.car_plate_number','like', '%' . $param['car_no'] . '%'];
            }
            if (isset($param['stime'], $param['etime'])  && $param['stime'] && $param['etime']) {
                $where[] = ['task.date', 'between', [$param['stime'], $param['etime']]];
            }
            if ($param['is_export'] == 1) {
                $param['limit'] = Db::table('xl_normal_task')->alias('task')->where([$where])->count();
            }
            $normalTask = Db::table('xl_normal_task')->alias('task')
                            ->join('xl_parnter_line line', 'task.line_id = line.id', 'left')
                            ->join('xl_company company', 'line.company_id = company.id', 'left')
                            ->join('xl_driver driver', 'task.driver_id = driver.id', 'left')
                            ->join('xl_cars car', 'task.car_id = car.id', 'left')
                            ->join('xl_normal_task_abnormal tab', 'task.id = tab.task_id', 'left')
                            ->where([$where])->limit(($param['page'] - 1) * $param['limit'], $param['limit'])
                            ->field('task.*,line.line_no,line.time_consume,line.network_ids,line.warehouse_ids,line.transport_name,tab.type abnormal_type,tab.pic1_url abnormal_pic1, tab.pic2_url abnormal_pic2, tab.pic3_url abnormal_pic3, tab.message abnormal_message')
                            ->order('task.id desc')
                            ->select()->toArray();

            foreach ($normalTask as $k => $v) {
                $list = "";
                $network_ids = explode(",", $v['network_ids']);
                $sql = "select id,name from xl_networks where id in ( " . $v['network_ids'] . " ) order by field (id," . $v["network_ids"] . ")";
                $res = Db::query($sql);
                foreach ($res as $k1 => $v1) {
                    if ($list == "") {
                        $list .= $v1['name'];
                    } else {
                        $list .= "," . $v1['name'];
                    }

                }

                $normalTask[$k]['networks_list'] = $list;

                $normalTask[$k]['driver_name'] = '';
                if ($v['driver_id'] > 0) {
                    $driverInfo = DriverModel::info($v['driver_id']);
                    if ($driverInfo) {
                        $normalTask[$k]['driver_name'] = $driverInfo['name'];
                    }
                }

                $normalTask[$k]['car_owner_type'] = 0;
                $normalTask[$k]['car_no'] = '';
                if ($v['car_id'] > 0) {
                    $carInfo = CarModel::info(['id' => $v['car_id']]);
                    $normalTask[$k]['car_owner_type'] = $carInfo ? $carInfo['owner_type'] : 0;
                    $normalTask[$k]['car_no'] = $carInfo ? $carInfo['car_plate_number'] : "";
                }

                $normalTask[$k]['task_status_text'] = self::escape_task_status($v['task_status']);

                $normalTask[$k]['order_count'] = 0;
                $normalTask[$k]['order_money'] = 0.00;
                if ($normalTask[$k]['task_type'] == 2) {
                    unset($param);
                    $param['datestr'] = date('Y-m-d', (strtotime($v['date']) - 60*60*24));
                    $param['network_ids'] = $v['network_ids'];
                    $param['page'] = 1;
                    $param['limit'] = 15;
                    $deliveryOrders = DeliveryOrderModel::lists($param);
                    foreach ($deliveryOrders['lists'] as $kdo => $vdo) {
                        $normalTask[$k]['order_count'] += count(explode(",", $vdo['link_order_ids']));
                        $normalTask[$k]['order_money'] += $vdo['order_money'];
                    }
                }

            }

            $count = Db::table('xl_normal_task')->alias('task')
                       ->join('xl_parnter_line line', 'task.line_id = line.id', 'left')
                       ->join('xl_company company', 'line.company_id = company.id', 'left')
                       ->join('xl_driver driver', 'task.driver_id = driver.id', 'left')
                       ->join('xl_cars car', 'task.car_id = car.id', 'left')
                       ->join('xl_normal_task_abnormal tab', 'task.id = tab.task_id', 'left')
                       ->where([$where])->count();

            //1 未开始  2 配送中   3 已结束(正常) 4 已结束(非正常)
            return ['list' => $normalTask, 'count' => $count];
        }catch(\Exception $e){
            halt("错误信息:".$e->getMessage()."错误行号:".$e->getLine()."错误文件:".$e->getFile());
        }

	}

	public static function escape_task_status($status)
	{
		// 1 未开始   2 (已开始)拣货中  3(已开始)送货中   4 已结束(正常) 5已结束(非正常) 6异常上报 7异常驳回
		switch ($status) {
			case 1: $ret = '未开始'; break;
			case 2: $ret = '拣货中'; break;
			case 3: $ret = '送货中'; break;
			case 4: $ret = '已完成'; break;
			case 5: $ret = '异常结束'; break;
			case 6: $ret = '异常上报'; break;
			case 7: $ret = '异常驳回'; break;
			default:$ret = '';break;
		}
		return $ret;
	}

	public static function detail($param) {
		$where[] = [
			'task.partner_id', '=', $param['partner_id'],
		];

		if ($param['task_id']) {
			$where[] = ['task.id', '=', $param['task_id']];
		}

		$normalTask = Db::table('xl_normal_task')->alias('task')
			->join('xl_parnter_line line', 'task.line_id = line.id', 'left')
			->join('xl_driver driver', 'task.driver_id = driver.id', 'left')
			->join('xl_cars cars', 'task.car_id = cars.id', 'left')
			->where([$where])
			->field('task.*,line.line_no,line.time_consume,line.driver_ids,line.car_id,line.network_ids,driver.name as driver_name,cars.car_plate_number')
			->find();
		// $normalTask['time_interval']='8:00-12:00<br/>14:00-18:00';
		$list = [];
		$warehouse_ids = explode(",", $normalTask['warehouse_ids']);
		foreach ($warehouse_ids as $k => $v) {
			$list[] = WarehouseModel::info($v);
		}
		$network_ids = explode(",", $normalTask['network_ids']);
		foreach ($network_ids as $k => $v) {
			$list[] = NetworksModel::info($v);
		}

		foreach ($list as $k1 => $v1) {
			//预计
			$list[$k1]['estimate'] = '*';
			//实际
			$list[$k1]['real'] = '*';
			$list[$k1]['tran_status'] = 1;
		}

		return ['normalTask' => $normalTask, 'list' => $list];
	}

	public static function details($param) {
		$where[] = [
			'task.partner_id', '=', $param['partner_id'],
		];

		if ($param['task_id']) {
			$where[] = ['task.id', '=', $param['task_id']];
		}

		$normalTask = Db::table('xl_normal_task')->alias('task')
			->join('xl_parnter_line line', 'task.line_id = line.id', 'left')
			->join('xl_driver driver', 'task.driver_id = driver.id', 'left')
			->join('xl_cars cars', 'task.car_id = cars.id', 'left')
			->where([$where])
			->field('task.*,line.line_no,line.time_consume,line.driver_ids,line.car_ids,line.network_ids,driver.name as driver_name,cars.car_plate_number')
			->find();
		$normalTask['total_mileage'] = $normalTask['total_mileage'] . "km";

		$list = [];
		// $warehouse_ids = explode(",", $normalTask['warehouse_ids']);
		// foreach ($warehouse_ids as $k => $v) {
		// 	$list[] = WarehouseModel::info($v, 1);
		// }

		$network_ids = explode(",", $normalTask['network_ids']);
		foreach ($network_ids as $k => $v) {
			$list[] = NetworksModel::info($v, 2);
		}
		$explode = explode("-", $normalTask['requirement_time']);
		$startTime = $normalTask['date'] . ' ' . $explode[0];
		$endCount = count($list);
		$i = 1;
		foreach ($list as $k1 => $v1) {
			
				$list[$k1]['order_count'] = 0;
				
				$info = Db::table('xl_normal_task_arrive_detail')->where('net_id', '=', $v1['id'])->where('type', $v1['type'])->where('task_id', $param['task_id'])->find();
				//预计
				if ($v1['type'] == 1) {
					$list[$k1]['estimate'] = $startTime;
						$list[$k1]['km_num'] = 0;
				} else {
					if ($k1 != $endCount - 1) {
						$targetInfo = $list[0];
						$i++;
						$kmNum = getdistances((float) $targetInfo['longitude'], (float) $targetInfo['dimension'], (float) $v1['longitude'], (float) $v1['dimension']);
						$kmNum = round($kmNum);
						$list[$k1]['km_num'] = $kmNum;
						$list[$k1]['estimate'] = date("Y-m-d H:i:s", strtotime($startTime) + $i * rand(20, 40) * 60);
					} else {
						$list[$k1]['km_num'] = 0;
						$list[$k1]['estimate'] = $normalTask['date'] . ' ' . $explode[1];
					}

					if ($normalTask['task_type'] == 2) {
						unset($where);
						$where[] = ['network_id', '=', $v1['id']];
						$where[] = ['tms_task_id', '=', $normalTask['id']];
						$where[] = ['datestr', '=', date('Y-m-d', strtotime($normalTask['date']) - 60*60*24)];
						$record = Db::table('xl_delivery_order')->where($where)->find();
						if ($record) {
							$list[$k1]['order_count'] = count(explode(',', $record['link_nos']));
						}
					}					
				}
				//实际
				if (!empty($info)) {
					$list[$k1]['real'] = $info['add_time'];
					$list[$k1]['real_sort'] = strtotime($info['add_time']);
				} else {
					$list[$k1]['real'] = '*';
					$list[$k1]['real_sort'] = 0;
				}
				if ($normalTask['task_status'] <= 2 && empty($info)) {
					$list[$k1]['tran_status'] = 1;
				} elseif ($normalTask['task_status'] > 2 && empty($info)) {
					$list[$k1]['tran_status'] = 0;
				} elseif (!empty($info)) {
					$list[$k1]['tran_status'] = 2;
				}

		} 

		array_multisort(array_column($list, 'real_sort'),SORT_ASC,$list);

		foreach ($list as $k1 => $v1) {
			$key = $k1-1;
			$key = $key < 0 ? 0 : $key;
			$targetInfo = $list[$key];
			$list[$k1]['time_consume'] = ceil(($v1['real_sort'] - $targetInfo['real_sort'])/60);
		}

		return ['normalTask' => $normalTask, 'list' => $list];
	}

	/**
	 * 获取所有仓库类型
	 * @return void
	 */
	public static function GetAllWarehouseType() {
		return Db::table('xl_warehouse_type')->where("status", "=", 1)
			->select();

	}

	/**
	 * 获取所有业务类型
	 * @return void
	 */
	public static function GetAllBussineType() {
		return Db::table('xl_business_type')->where("status", "=", 1)
			->select();

	}

	/**
	 * 新增网点
	 * @return void
	 */
	public static function add($data) {
		return Db::table('xl_networks')->insert($data);

	}

	/**
	 * 新增所有仓库
	 * @return void
	 */
	public static function edit($data, $id) {
		return Db::table('xl_networks')->where('id', '=', $id)->update($data);

	}

	/**
	 * 删除仓库
	 * @return void
	 */
	public static function del($id) {
		return Db::table('xl_networks')->where('id', '=', $id)->update(['status' => 3]);

	}

	//配送信息

	public static function distributionList($param) {
        $source = PartnerUser::where('id',request()->param('uid'))->value('source');
        $where[] = [
            'uid', 'like',$source."%" ,
        ];
		$where[] = ['status', '=', 1];
		$where[] = [
			'partner_id', '=', $param['partner_id'],
		];
		if ($param['is_export'] == 1) {
			$param['limit'] = Db::table('xl_normal_task_detail')->where([$where])->count();
		}
		$param['page'] = ($param['page'] - 1) < 0 ? 1 : $param['page'];
		$list = Db::table('xl_normal_task_detail')->where($where)
			->limit(($param['page'] - 1) * $param['limit'], $param['limit'])
			->order('id desc')
			->select()->toArray();
		foreach ($list as $k => $v) {
			$list[$k]['warehouse_name'] = (WarehouseModel::info($v['warehouse_id']))['name'];
			$list[$k]['network_name'] = (NetworksModel::info($v['network_id']))['name'];
			$taskInfo = self::task_info($v['task_id']);
			$list[$k]['no'] = $taskInfo['no'];
			if ($taskInfo['driver_id']) {
				$driverInfo = DriverModel::info($taskInfo['driver_id']);
				if ($driverInfo) {
					$list[$k]['driver_name'] = $driverInfo['name'];
				}else{
					$list[$k]['driver_name'] = '';
				}
			}

			//business_type_id 业务类型  业务类型1 社区团购 2快递 3 经销商
		}
		$count = Db::table('xl_normal_task_detail')->where($where)->count();
		return ['list' => $list, 'count' => $count];
	}

	public static function info($id) {
		return Db::table('xl_normal_task')->where("id", '=', $id)->find();
	}

	public static function task_info($id) {
		return Db::table('xl_normal_task')->where("id", '=', $id)->field('id,driver_id,no')->find();
	}

	//获取今日任务路线名称
	public static function lineList($param) {
		$where[] = ['task.partner_id', '=', $param['partner_id']];
		$where[] = ['task.status', '=', 1];
		$where[] = ['task.date', '=', $param['now_time']];
		$data = Db::table('xl_normal_task')->alias('task')
			->join('xl_parnter_line line', 'task.line_id = line.id', 'left')
			->where([$where])
			->field('task.id,line.line_no')
			->select()
			->toArray();
		return $data;

	}

	//根据ID获取详情
	public static function mapInfo($param) {
		$where[] = ['partner_id', '=', $param['partner_id']];
		$where[] = ['status', '=', 1];
		$where[] = ['id', '=', $param['task_id']];

		$data = Db::table('xl_normal_task')->where([$where])->field('id,warehouse_ids,network_ids')->find();
		if (!empty($data)) {
			$array = [];
			$warehouseIdsArr = explode(',', $data['warehouse_ids']);
			$netWorkIdsArr = explode(',', $data['network_ids']);
			$warehouseList = Db::table('xl_warehouse')->where('id', 'in', $data['warehouse_ids'])->field('id,name,longitude,dimension')->select()->toArray();
			$networkList = Db::table('xl_networks')->where('id', 'in', $data['network_ids'])->field('id,name,longitude,dimension')->select()->toArray();
			foreach ($warehouseIdsArr as &$val) {
				foreach ($warehouseList as &$v) {
					$v['type'] = 'warehouse';
					$v['count'] = 0;
					if ($v['id'] == $val) {
						array_push($array, $v);
					}
				}
			}
			foreach ($netWorkIdsArr as &$val) {
				foreach ($networkList as &$v) {
					$v['type'] = 'networks';
					$v['count'] = 0;
					if ($v['id'] == $val) {
						array_push($array, $v);
					}
				}
			}
			$data['route'] = $array;
			$data['recommend_driver'] = '';
			$data['recommend_car'] = '';
		}
		return $data;

	}

	//获取线路详情
	public static function historyRouteDetails($param) {

		$where[] = ['partner_id', '=', $param['partner_id']];
		$where[] = ['status', '=', 1];
		$where[] = ['id', '=', $param['task_id']];
		$data = Db::table('xl_normal_task')->where([$where])->field('id,warehouse_ids,network_ids')->find();
		$array = [];
		$infoArr = [];
		$warehouseIdsArr = explode(',', $data['warehouse_ids']);
		$netWorkIdsArr = explode(',', $data['network_ids']);
		$warehouseList = Db::table('xl_warehouse')->where('id', 'in', $data['warehouse_ids'])->field('id,name,longitude,dimension as latitude')->select()->toArray();
		$networkList = Db::table('xl_networks')->where('id', 'in', $data['network_ids'])->field('id,name,longitude,dimension as latitude')->select()->toArray();
		$taskInfo = self::info($param['task_id']);
		if (!empty($taskInfo['driver_id'])) {
			$infoArr['driver_name'] = DriverModel::info($taskInfo['driver_id'])['name'];
		} else {
			$infoArr['driver_name'] = '';
		}
		$infoArr['date_time'] = $taskInfo['add_time'];
		$infoArr['count'] = $taskInfo['network_count'] + $taskInfo['warehouse_count'];
		$infoArr['delivery_status'] = $taskInfo['delivery_status'];
		if (!empty($taskInfo['car_id'])) {
			$id['id'] = $taskInfo['car_id'];
			$infoArr['car_number'] = CarModel::info($id)['car_plate_number'];
			$infoArr['equi_identity'] = CarModel::info($id)['equi_identity'];
		} else {
			$infoArr['car_number'] = '';
		}
		foreach ($warehouseIdsArr as &$val) {
			foreach ($warehouseList as &$v) {
				$v['type'] = 1;
				if ($v['id'] == $val) {
					array_push($array, $v);
				}
			}
		}
		foreach ($netWorkIdsArr as &$val) {
			foreach ($networkList as &$v) {
				$v['type'] = 2;
				if ($v['id'] == $val) {
					array_push($array, $v);
				}
			}
		}
		$lastOrigin = $array[count($array) - 1];

		foreach ($array as $k => $v) {
			$arrivalInfo = Db::table('xl_normal_task_arrive_detail')
				->where(['type' => $v['type'], 'task_id' => $data['id'], 'net_id' => $v['id']])
				->field('id,net_id,type,add_time')->find();
			$array[$k]['goods_count'] = 0;
			if (!empty($arrivalInfo)) {
				$array[$k]['arrival_info'] = $arrivalInfo;
			} //else{
			//     unset($array[$k]);
			// }

		}
		$array = array_values($array);
		$count = count($array);
		// dump($array[5+1]);die;
		foreach ($array as $k => $v) {
			if ($k != 0 && !isset($array[$k]['arrival_info'])) {
				continue;
			}
			if (isset($array[$k + 1]['arrival_info']) && isset($array[$k]['arrival_info']['add_time'])) {
				//  $array[$k+1]['arrival_info']['use_time_min'] =floor((strtotime($array[$k+1]['arrival_info']['add_time']) - strtotime($array[$k]['arrival_info']['add_time']))/60) ;
				$array[$k]['arrival_info']['use_time_min'] = floor((strtotime($array[$k + 1]['arrival_info']['add_time']) - strtotime($array[$k]['arrival_info']['add_time'])) / 60);
			} else {
				if (isset($array[$k]['arrival_info'])) {
					$array[$k]['arrival_info']['use_time_min'] = "0";
				}
				// // }
				// }
				// if($k!=0){
				// if($k!=$count-1){
				//     $array[$k]['arrival_info']['use_time_min'] = floor((strtotime($array[$k+1]['arrival_info']['add_time']) - strtotime($array[$k]['arrival_info']['add_time']))/60) ;
				// }

			}
		}

		// foreach ($array as $k => $v) {
		//     if (!empty($array[$k + 1]['arrival_info']) && $k != 0) {
		//         $array[$k]['arrival_info']['use_time_min'] = "5";
		//                     //   $array[$k]['arrival_info']['use_time_min'] = floor((strtotime($array[$k]['arrival_info']['add_time']) - strtotime($array[$k-1]['arrival_info']['add_time']))/60);
		//     } else {
		//         if(!empty($array[$k]['arrival_info'])){
		//             $array[$k]['arrival_info']['use_time_min'] = "0";
		//         }
		//     }
		// }
		// $filterArr = new \stdClass;
		//   if(!empty($infoArr['car_number'])){
		//     $explode = explode("-",$taskInfo['requirement_time']);
		//     $startTime= $taskInfo['date'] .  ' '.$explode[0];
		//     $endTime = $taskInfo['date'].  ' '.$explode[1];

		//     $carGpsInfo = Db::name('gpsinfo')
		//         ->where('license_plate',$infoArr['car_number'])
		//         ->whereTime('add_time', 'between', [$startTime,$endTime])
		//         ->field('id,longitude,latitude,speed,direction')->select()->toArray();
		//     $filterArr = [];
		//     if (!empty($carGpsInfo)) {
		//         foreach ($carGpsInfo as $key => $value) {
		//             if($key == 0){
		//                 $filterArr[] = $value;
		//             }else{
		//                 $last = $filterArr[count($filterArr) - 1];
		//                 $distance = get_distance([$last['longitude'], $last['latitude']], [$value['longitude'], $value['latitude']], false);
		//                 if($distance>10){
		//                     array_push($filterArr,$value);
		//                 }
		//             }
		//         }
		//     }
		// }

		// // dump($carGpsInfo);die;
		// $list['list'] = $array;
		// $list['info'] = $infoArr;
		// $list['gps_info'] = $filterArr;
		$backAndForthArr = new \stdClass;
		if (!empty($infoArr['equi_identity'])) {
			$explode = explode("-", $taskInfo['requirement_time']);
			if (strlen($explode[0]) == 4) {
				$explode[0] = '0' . $explode[0];
			}
			// $startExplode = explode(":",$explode[0]);
			// if($startExplode[0]<'10'){
			//     $startExplode[0] = '0'.$startExplode[0]
			// }
			$startTime = $taskInfo['date'] . ' ' . $explode[0];
			// dump($startTime);die;
			$endTime = $taskInfo['date'] . ' ' . $explode[1];
			$endTime = date("Y-m-d H:i:s", strtotime($endTime) + 7200);

			// $carGpsInfo = Db::name('gpsinfo')
			//     ->where('license_plate', $infoArr['car_number'])
			//     ->whereTime('add_time', 'between', [$startTime, $endTime])
			//     ->field('id,longitude,latitude,speed,direction,add_time')->select()->toArray();

			$carGpsInfo = Db::connect('mongo')->table('tms_gpsinfo')
				->where('equiidentity', '=', $infoArr['equi_identity'])
				->where('addtime', '<', $endTime)
				->where('addtime', '>', $startTime)
				->field('id,longitude,latitude,speed,direction,addtime')
				->select()->toArray();
			// dump($carGpsInfo);die;
			$filterArr = [];
			if (!empty($carGpsInfo)) {
				foreach ($carGpsInfo as $key => $value) {
					if ($key == 0) {
						$filterArr[] = $value;
					} else {
						$last = $filterArr[count($filterArr) - 1];
						$distance = get_distance([$last['longitude'], $last['latitude']], [$value['longitude'], $value['latitude']], false);
						if ($distance > 10) {
							array_push($filterArr, $value);
						}
					}
				}
			}
			for ($i = count($array) - 1; $i > 0; $i--) {
				$lastOrigin = $array[$i];
				$lastArrivalInfo = Db::table('xl_normal_task_arrive_detail')
					->where(['type' => $lastOrigin['type'], 'task_id' => $data['id'], 'net_id' => $lastOrigin['id']])
					->field('id,net_id,type,add_time')->find();
				if (!empty($lastArrivalInfo)) {
					break;
				}
			}
			// echo 77777;
			// dump($lastArrivalInfo);die;
			// $lastArrivalInfo = Db::table('xl_normal_task_arrive_detail')
			//     ->where(['type' => $lastOrigin['type'], 'task_id' => $data['id'], 'net_id' => $lastOrigin['id']])
			//     ->field('id,net_id,type,add_time')->find();
			// $lastArrNew = [];
			// for($i=0;$i<=count($array) - 1,$i++){
			//     $lastOrigin = $array[$i];
			//     $lastArrivalInfo = Db::table('xl_normal_task_arrive_detail')
			//     ->where(['type' => $lastOrigin['type'], 'task_id' => $data['id'], 'net_id' => $lastOrigin['id']])
			//     ->field('id,net_id,type,add_time')->find
			//     if(!empty($lastArrivalInfo)){
			//         array_push($lastArrNew,$lastArrivalInfo)
			//     }
			// }
			$backAndForthArr = [];
			if (!empty($lastArrivalInfo)) {
				foreach ($filterArr as $item) {
					if ($item['addtime'] < $lastArrivalInfo['add_time']) {
						$backAndForthArr['go'][] = $item;
					} else {
						$backAndForthArr['back'][] = $item;
					}
				}
			}
		}
		$list['list'] = $array;
		$list['info'] = $infoArr;
		$list['gps_info'] = $backAndForthArr;
		return $list;
	}

	public static function getTrack($param) {
		//基本信息
		$url = 'http://gpstime.xianlian.cc/api/mileage';
		$basic = [];
		$carNumber = Db::table('xl_cars')->where('id', $param['car_id'])->value('car_plate_number');
		$carGpsInfo = Db::connect('mongo')->table('tms_gpsinfo')
			->where('licenseplate', '=', $carNumber)
			->field('id,longitude,latitude,speed,direction,addtime')
			->find();
		// dump($carGpsInfo);die;
		$where[] = ['status', '=', 1];
		$where[] = ['slice_time', 'between', [$param['stime'], $param['etime']]];
		$where[] = ['car_id', '=', $param['car_id']];
		$taskData = Db::table('xl_normal_task')->where([$where])->field('id,warehouse_ids,network_ids,no,requirement_time,date')->select()->toArray();
		if (!empty($taskData)) {
			$basic['task_no'] = implode(",", array_column($taskData, 'no'));
		} else {
			$basic['task_no'] = '';
		}
		if (empty($carGpsInfo)) {
			return 10001;
		}
		$gpsMobile = Db::table('xl_cars')->where('id', $param['car_id'])->value('gps_mobile');
		if (empty($gpsMobile)) {
			return 10002;
		}
		if ($carGpsInfo['speed'] != 0) {
			$basic['now_status'] = 1;
		} else {
			$basic['now_status'] = 0;
		}
		$basic['car_number'] = $carNumber;
		$basic['now_postion'] = $carGpsInfo['longitude'] . "," . $carGpsInfo['latitude'];
		$basic['section'] = $param['stime'] . '-' . $param['etime'];
		$basicPost = https_request_one($url, ['mobile' => stripslashes($gpsMobile), 'car_number' => stripslashes($carNumber), 's_time' => stripslashes($param['stime']), 'e_time' => stripslashes($param['etime'])]);
		$basicPost = json_decode($basicPost, true);
		if ($basicPost['code'] == 200) {
			$basic['millage_length'] = round($basicPost['data']['millage_length'], 2);
		} else {
			$basic['millage_length'] = '502.00';
		}
		//轨迹跟踪
		$traUrl = 'http://gpstime.xianlian.cc/api/track_list';
		$traPost = https_request_one($traUrl, ['car_id' => stripslashes($param['car_id']), 'car_number' => stripslashes($carNumber), 's_time' => stripslashes($param['stime']), 'e_time' => stripslashes($param['etime'])]);
		$traPost = json_decode($traPost, true);
		if ($traPost['code'] == 200) {
			$abCount = 0;
			foreach ($traPost['data']['xlTrackList'] as $vv) {
				if ($vv['test_type'] == 3) {
					$abCount++;
				}
			}
			$traData['all_count'] = count($traPost['data']['xlTrackList']);
			$traData['abnormal_count'] = $abCount;
			$traData['millage_length'] = $basic['millage_length'];
			$traData['list'] = $traPost['data']['xlTrackList'];
		} else {
			$traData['all_count'] = 0;
			$traData['abnormal_count'] = 0;
			$traData['millage_length'] = 0;
			$traData['list'] = [];
		}
		//任务信息
		if (!empty($taskData)) {
			foreach ($taskData as $key => $value) {
				$array = [];
				$infoArr = [];
				$warehouseIdsArr = explode(',', $value['warehouse_ids']);
				$netWorkIdsArr = explode(',', $value['network_ids']);
				$warehouseList = Db::table('xl_warehouse')->where('id', 'in', $value['warehouse_ids'])->field('id,name,longitude,dimension as latitude')->select()->toArray();
				$networkList = Db::table('xl_networks')->where('id', 'in', $value['network_ids'])->field('id,name,longitude,dimension as latitude')->select()->toArray();
				$taskInfo = self::info($value['id']);
				if (!empty($taskInfo['driver_id'])) {
					$infoArr['driver_name'] = DriverModel::info($taskInfo['driver_id'])['name'];
				} else {
					$infoArr['driver_name'] = '';
				}
				if (!empty($taskInfo['car_id'])) {
					$id['id'] = $taskInfo['car_id'];
					$infoArr['car_number'] = CarModel::info($id)['car_plate_number'];
					$infoArr['equi_identity'] = CarModel::info($id)['equi_identity'];
				} else {
					$infoArr['car_number'] = '';
				}
				foreach ($warehouseIdsArr as &$val) {
					foreach ($warehouseList as &$v) {
						$v['type'] = 1;
						if ($v['id'] == $val) {
							array_push($array, $v);
						}
					}
				}
				foreach ($netWorkIdsArr as &$val) {
					foreach ($networkList as &$v) {
						$v['type'] = 2;
						if ($v['id'] == $val) {
							array_push($array, $v);
						}
					}
				}
				$lastOrigin = $array[count($array) - 1];
				foreach ($array as $k => $v) {
					$arrivalInfo = Db::table('xl_normal_task_arrive_detail')
						->where(['type' => $v['type'], 'task_id' => $value['id'], 'net_id' => $v['id']])
						->field('id,net_id,type,add_time')->find();
					if (!empty($arrivalInfo)) {
						$array[$k]['arrival_info'] = $arrivalInfo;
					}
				}
				$array = array_values($array);

				$backAndForthArr = new \stdClass;
				if (!empty($infoArr['equi_identity'])) {
					$explode = explode("-", $taskInfo['requirement_time']);
					if (strlen($explode[0]) == 4) {
						$explode[0] = '0' . $explode[0];
					}
					$startTime = $taskInfo['date'] . ' ' . $explode[0];
					$endTime = $taskInfo['date'] . ' ' . $explode[1];
					$infoArr['task_status'] = $taskInfo['task_status'];
					$infoArr['no'] = $taskInfo['no'];
					$infoArr['section'] = $startTime . '-' . $endTime;
					$basicPost = https_request_one($url, ['mobile' => stripslashes($gpsMobile), 'car_number' => stripslashes($carNumber), 's_time' => stripslashes($startTime), 'e_time' => stripslashes($endTime)]);
					$basicPost = json_decode($basicPost, true);
					//   dump($basicPost);
					if ($basicPost['code'] == 200) {
						$infoArr['millage_length'] = round($basicPost['data']['millage_length'], 2);
						$infoArr['time_length'] = round($basicPost['data']['time_length'], 2);
					} else {
						$infoArr['millage_length'] = '502.00';
						$infoArr['time_length'] = '404.00';
					}
					$endTime = date("Y-m-d H:i:s", strtotime($endTime) + 7200);
					$carGpsInfo = Db::connect('mongo')->table('tms_gpsinfo')
						->where('equiidentity', '=', $infoArr['equi_identity'])
						->where('addtime', '<', $endTime)
						->where('addtime', '>', $startTime)
						->field('id,longitude,latitude,speed,direction,addtime')
						->select()->toArray();
					$filterArr = [];
					if (!empty($carGpsInfo)) {
						foreach ($carGpsInfo as $keyc => $valuec) {
							if ($keyc == 0) {
								$filterArr[] = $valuec;
							} else {
								$last = $filterArr[count($filterArr) - 1];
								$distance = get_distance([$last['longitude'], $last['latitude']], [$valuec['longitude'], $valuec['latitude']], false);
								if ($distance > 10) {
									array_push($filterArr, $valuec);
								}
							}
						}
					}
					for ($i = count($array) - 1; $i > 0; $i--) {
						$lastOrigin = $array[$i];
						$lastArrivalInfo = Db::table('xl_normal_task_arrive_detail')
							->where(['type' => $lastOrigin['type'], 'task_id' => $value['id'], 'net_id' => $lastOrigin['id']])
							->field('id,net_id,type,add_time')->find();
						if (!empty($lastArrivalInfo)) {
							continue;
						}
					}
					$backAndForthArr = [];
					if (!empty($lastArrivalInfo)) {
						foreach ($filterArr as $item) {
							if ($item['addtime'] < $lastArrivalInfo['add_time']) {
								$backAndForthArr['go'][] = $item;
							} else {
								$backAndForthArr['back'][] = $item;
							}
						}
					}
				}
				$list[$key]['list'] = $array;
				$list[$key]['info'] = $infoArr;
				$list[$key]['gps_info'] = $backAndForthArr;
			}
			$carGpsInfoAll = Db::connect('mongo')->table('tms_gpsinfo')
				->where('equiidentity', '=', $infoArr['equi_identity'])
				->where('addtime', '<', $param['etime'])
				->where('addtime', '>', $param['stime'])
				->field('id,longitude,latitude,speed,direction,addtime')
				->select()->toArray();
			$filterArrAll = [];
			if (!empty($carGpsInfoAll)) {
				foreach ($carGpsInfoAll as $keyc => $valuec) {
					if ($keyc == 0) {
						$filterArrAll[] = $valuec;
					} else {
						$last = $filterArrAll[count($filterArrAll) - 1];
						$distance = get_distance([$last['longitude'], $last['latitude']], [$valuec['longitude'], $valuec['latitude']], false);
						if ($distance > 10) {
							array_push($filterArrAll, $valuec);
						}
					}
				}
			}
		} else {
			$infoArr['equi_identity'] = CarModel::info(['id' => $param['car_id']])['equi_identity'];
			//   dump($param['car_id']);die;
			$carGpsInfoAll = Db::connect('mongo')->table('tms_gpsinfo')
				->where('equiidentity', '=', $infoArr['equi_identity'])
				->where('addtime', '<', $param['etime'])
				->where('addtime', '>', $param['stime'])
				->field('id,longitude,latitude,speed,direction,addtime')
				->select()->toArray();
			// dump($infoArr);die;
			$filterArrAll = [];
			if (!empty($carGpsInfoAll)) {
				foreach ($carGpsInfoAll as $keyc => $valuec) {
					if ($keyc == 0) {
						$filterArrAll[] = $valuec;
					} else {
						$last = $filterArrAll[count($filterArrAll) - 1];
						$distance = get_distance([$last['longitude'], $last['latitude']], [$valuec['longitude'], $valuec['latitude']], false);
						if ($distance > 10) {
							array_push($filterArrAll, $valuec);
						}
					}
				}
			}
			$list = [];
		}
		return ['basic_info' => $basic, 'task_data' => $list, 'all_gps_info' => $filterArrAll, 'track_list' => $traData];
	}

}
